package pers.vinsonws.jianghu.serverspring.session;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.vinsonws.jianghu.util.User;

import java.util.HashMap;
import java.util.Map;

/**
 * @auther vinsonws
 * @date 2018/10/30 16:47
 * 以User 的 ID 作为session的ID, 此ID 非 user的登录ID。
 */
public class NetSession {
    private static final Logger log = LoggerFactory.getLogger(NetSession.class);


    private Channel channel;

    private User user;

    /** ip地址 */
    private String ipAddr;

    private boolean reconnected;

    private boolean online;

    /** 拓展用 保存一些个数据  */
    private Map<String, Object> attribute = new HashMap<>();

    public NetSession(Channel channel) {
        this.channel = channel;
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getIpAddr() {
        return ipAddr;
    }

    public void setIpAddr(String ipAddr) {
        this.ipAddr = ipAddr;
    }

    public boolean isReconnected() {
        return reconnected;
    }

    public void setReconnected(boolean reconnected) {
        this.reconnected = reconnected;
    }

    public Map<String, Object> getAttribute() {
        return attribute;
    }

    public void setAttribute(Map<String, Object> attribute) {
        this.attribute = attribute;
    }

    public boolean isClose() {
        if (channel == null) {
            return true;
        }
        return !channel.isActive() ||
                !channel.isOpen();
    }

    public void setOnline(boolean online) {
        this.online = online;
    }

    public boolean isOnline() {
        return online;
    }
    /**
     * 关闭session
     * @param reason {@link SessionCloseReason}
     */
    public void close(SessionCloseReason reason) {
        try{
            if (this.channel == null) {
                return;
            }
            if (channel.isOpen()) {
                channel.close();
                log.info("close session[{}], reason is {}", getUser().getId(), reason);
            }else{
                log.info("session[{}] already close, reason is {}", getUser().getId(), reason);
            }
        }catch(Exception e){
        }
    }
}
